package dhz.storage.configurations;

import dhz.storage.util.JwtToken;
import dhz.storage.util.JwtUtil;
import dhz.storage.util.JwtRedisUtil;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Locale;

public class JwtRealm extends AuthorizingRealm {

    @Autowired
    JwtRedisUtil redis_util;

    @Override
    public boolean supports(AuthenticationToken token){
        return token instanceof JwtToken;
    }
    /**
     * 授权过程，因为这个项目相对简单，所以不用考虑授权
     * */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 鉴权过程，需要考虑这个 authenticationToken 中的jwt在不在Redis中存着
     * */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        JwtToken token = (JwtToken) authenticationToken;
        String identification = JwtUtil.getIdentification(token.getPrincipal().toString());
        // 判断一下redis里面有没有，如果没有就不算数
        if(!redis_util.hasID(identification)){
            throw new UnknownAccountException();
        }
        if(identification == null){
            throw new UnknownAccountException();
        }else {
            // 此处需要对token里面蕴藏的学号/工号信息做一些处理
            identification = "u" + identification;
            identification = identification.toLowerCase(Locale.ROOT);
            return new SimpleAuthenticationInfo(identification, token.getPrincipal(), "JwtRealm");
        }
    }
}
